package com.feicheng.service.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.cache.Cache;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Category;
import com.feicheng.persistence.entity.CategoryDetail;
import com.feicheng.persistence.entity.Image;
import com.feicheng.persistence.entity.Product;
import com.feicheng.persistence.entity.ProductImage;
import com.feicheng.persistence.entity.Sample;
import com.feicheng.persistence.model.CategoryPagePojo;
import com.feicheng.persistence.model.CategoryPojo;
import com.feicheng.persistence.model.ProductPagePojo;
import com.feicheng.persistence.service.ICategoryDetailService;
import com.feicheng.persistence.service.ICategoryService;
import com.feicheng.persistence.service.IImageService;
import com.feicheng.persistence.service.IProductImageService;
import com.feicheng.persistence.service.IProductService;
import com.feicheng.persistence.service.ISampleService;
import com.feicheng.persistence.service.impl.ProductServiceImpl;
import com.feicheng.service.IFProductService;

@Service
public class FProductServiceImpl implements IFProductService {

    @Autowired
    ICategoryService categoryService;
    
    @Autowired
    ICategoryDetailService categoryDetailService;
    
    @Autowired
    IImageService imageService;
    
    @Autowired
    IProductService productService;
    
    @Autowired
    IProductImageService productImageService;

    @Autowired
    Cache cache;

    @Autowired
    ProductServiceImpl productServiceImpl;
    
    @Autowired
    ISampleService sampleService;
    
    @Autowired
    IFProductService productServiceCahe;
    
    //格式化categorys方法
    private String  formatCategorys(String categorys) {
    	 JSONArray categorysList = JSONObject.parseArray(categorys);
         String allcategorys = "";
         for (int i = 0; i < categorysList.size(); i++) {
             String adc = categorysList.get(i).toString();  
             JSONObject jsonObject = JSONObject.parseObject(adc);
             String json = jsonObject.getString("name").replaceAll("■", " ").trim();
             allcategorys = allcategorys +json + "/";

         }
    	return allcategorys;
	}
    @Override
    public synchronized void initCategoryCache() {
        JSONObject categoryCache = new JSONObject();

        List<? extends Category> all = this.allCategoryForData();

        for (Category category: all) {
        	CategoryPagePojo cp = (CategoryPagePojo) category;
            CategoryPojo currentPojo = new CategoryPojo(cp);
            currentPojo.setImageUrl(cp.getUrl());
            categoryCache.put(category.getCategoryId().toString(), currentPojo);

            if (category.getLevel() == 0) {
                continue;
            } else {
                CategoryPojo pCategory = categoryCache.getObject(category.getPId().toString(), CategoryPojo.class);
                if(pCategory != null) {
                	pCategory.getSubCategory().add(currentPojo);
                }
            }
        }

        cache.put("category", categoryCache);
    }

    @Override
    public List<Category> getSubCategory(Integer categoryId) {
        CategoryPojo c = cache.getJSONObject("category").getObject(categoryId.toString(), CategoryPojo.class);
        return c.getSubCategory();
    }

    @Override
    public ResultInfo getCategory(Integer categoryId) {
        return ResultInfo.success(cache.getJSONObject("category").get(categoryId.toString()));
    }

    @Override
    public List<? extends Category> allCategoryForData() {

        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.orderByAsc("level", "p_id", "category_id");

        return categoryService.selectCategorysAll(categoryQueryWrapper);
    }

    @Override
    public JSONArray allCurrentCategoryIds(Integer categoryId, JSONArray result) {

        JSONObject categoryCache = cache.getJSONObject("category");
        CategoryPojo currentCategory = categoryCache.getObject(categoryId.toString(), CategoryPojo.class);

        if (currentCategory.getSubCategory().size() > 0) {
            for (Category category : currentCategory.getSubCategory()) {
                CategoryPojo cp = (CategoryPojo) category;
                result = allCurrentCategoryIds(cp.getCategoryId(), result);
            }
        }

        result.add(currentCategory.getCategoryId());

        return result;

    }
    
    //获得父级方法
    private LinkedList<CategoryPojo> categoryPojoList(Integer categoryId, LinkedList<CategoryPojo> categoryPojoList) {
    	JSONObject categoryObject = cache.getJSONObject("category");
    	if( null != categoryId ) {
    		CategoryPojo pPojo = categoryObject.getObject(categoryId.toString(), CategoryPojo.class);
        	categoryPojoList.addFirst(pPojo);
        	//递归
        	if (null == pPojo.getPId()) {
        		return categoryPojoList;
        	} else {
        		return this.categoryPojoList(pPojo.getPId(), categoryPojoList);
        	}
    	}else {
    		return categoryPojoList;
		}
    	
    }

    /**
     * 获取分类详细信息
     * @param categoryId
     * @return image图片信息 categoryDetails分类详情信息 category分类信息 pCategorys父类分类信息
     */
	@Override
	public ResultInfo getCategoryDetail(Integer categoryId) {
		
		JSONObject result = new JSONObject();
		productServiceCahe.initCategoryCache();
		
		// 取得category详细
		JSONObject categoryObject = cache.getJSONObject("category");
		CategoryPojo currentPojo = categoryObject.getObject(categoryId.toString(), CategoryPojo.class);

//		Category c = categoryService.getById(categoryId);
//		CategoryPojo currentPojo = new CategoryPojo(c);
//		currentPojo.setCategoryId(c.getCategoryId());
//		currentPojo.setImgId(c.getImgId());
//		currentPojo.setName(c.getName());
//		currentPojo.setLevel(c.getLevel());
//		currentPojo.setPId(c.getPId());
//		currentPojo.setStatu(c.getStatu());
					
		LinkedList<CategoryPojo> categoryPojoList = new LinkedList<CategoryPojo>();
		categoryPojoList = this.categoryPojoList(currentPojo.getPId(), categoryPojoList);
		result.put("category", currentPojo);
		result.put("pCategorys", categoryPojoList);
		
		
		// 取得category detail详细
		QueryWrapper<CategoryDetail> categoryDetailWrapper = new QueryWrapper<>();
		categoryDetailWrapper.eq("category_id", currentPojo.getCategoryId());
		
		List<CategoryDetail> categoryDetails = categoryDetailService.list(categoryDetailWrapper);
		result.put("categoryDetails", categoryDetails);
		
		// 取得 image 详细
		Image image = imageService.getById(currentPojo.getImgId());
		result.put("image", image);
		
		return ResultInfo.success(result);
	}

	/**
     * 获取分类分页信息
     * @param
     * @return
     */
	@Override
	public ResultInfo getCagetorysByPage(Category category, Integer current, Integer size) {
		
//		Page<CategoryPagePojo> page = new Page<CategoryPagePojo>(current, size);
//		
//		QueryWrapper<CategoryPagePojo> queryWrapperCategoryPagePojo = new QueryWrapper<>();
//		
//		queryWrapperCategoryPagePojo.gt("c.category_id", 0);
//		
//		if (null != category.getPId()) {
//			queryWrapperCategoryPagePojo.eq("c.p_id", category.getPId());
//		}
//		
//		if (null != category.getLevel()) {
//			queryWrapperCategoryPagePojo.eq("c.level", category.getLevel());
//		}
//		
//		if (null != category.getName()) {
//			queryWrapperCategoryPagePojo.like("c.name", category.getName());
//		}
//		
//		if (null != category.getStatu()) {
//			queryWrapperCategoryPagePojo.eq("c.statu", category.getStatu());
//		}
		
		  Page<CategoryPagePojo> page = new Page<CategoryPagePojo>(current, size);
		  
		  QueryWrapper<CategoryPagePojo> queryWrapperCategoryPagePojo = new QueryWrapper<>();
		  
		  queryWrapperCategoryPagePojo.gt("c.category_id", 0);
		  
		  //用于 父级名称查询
		  if (category.getName().contains("/")) {
		  String[] s = category.getName().split("/");
		  //queryWrapperCategoryPagePojo.like("c.name",s[1]);
		  QueryWrapper<Category> queryWrapperSub = new QueryWrapper<>();
		  queryWrapperSub.eq("name", s[1]);//取到选择的父级 
		  Category ps = categoryService.getOne(queryWrapperSub);
		   
		  queryWrapperCategoryPagePojo.eq("c.p_id", ps.getCategoryId());
		   
		   queryWrapperCategoryPagePojo.like("c.name",s[0]);
		  }else if (category.getName().contains("/") == false && category.getName() != null) {
		   queryWrapperCategoryPagePojo.like("c.name", category.getName());
		  }
		  
		  if (null != category.getLevel()) {
		   queryWrapperCategoryPagePojo.eq("c.level", category.getLevel());
		  }
		  
		  if (null != category.getPId()) {
		   queryWrapperCategoryPagePojo.eq("c.p_id", category.getPId());
		  }
		   
		  if (null != category.getStatu()) {
		   queryWrapperCategoryPagePojo.eq("c.statu", category.getStatu());
		  }
		
		return ResultInfo.success(categoryService.selectCategorysByPage(page, queryWrapperCategoryPagePojo));
	}

	
	/**
     * 新增分类信息
     * @param
     * @return
     */
	@Transactional
	@Override
	public ResultInfo newCategoryInfo(Category category, String url, String contant) {
		//更新image表
		Image image = new Image();
		image.setUrl(url);
		imageService.save(image);
		
		//更新category表
		category.setImgId(image.getImgId());
		categoryService.save(category);
		
		//更新categoryDetail表
		CategoryDetail categoryDetail = new CategoryDetail();
		categoryDetail.setContant(contant);
		categoryDetail.setCategoryId(category.getCategoryId());
		categoryDetailService.save(categoryDetail);
		productServiceCahe.initCategoryCache();
		return ResultInfo.success();
	}
	
	/**
     * 删除分类信息
     * @param categoryId 分类ID
     * @return
     */
	@Transactional
	@Override
	public ResultInfo deleteCategoryInfo(Integer categoryId) {
		//根据ID查category
		Category category = categoryService.getById(categoryId);
		
		//修改image表中的dFlg 
		Image image = new Image();
		QueryWrapper<Image> imageQueryWrapper = new QueryWrapper<Image>();
		imageQueryWrapper.eq("img_id", category.getImgId());
		image.setDFlg(true);
		imageService.update(image, imageQueryWrapper);
		
		//删除detail表中的信息
		QueryWrapper<CategoryDetail> categoryDetailQueryWrapper = new QueryWrapper<CategoryDetail>();
		categoryDetailQueryWrapper.eq("category_id", categoryId);
		categoryDetailService.remove(categoryDetailQueryWrapper);
		
		//删除category主表
		categoryService.removeById(categoryId);
	
		return ResultInfo.success();
	}
	
	/**
     * 获取产品详细信息
     * @param productId
     * @return image图片信息  product产品信息
     */
	
	@Override
	public ResultInfo getProductDetail(Integer productId) {
		
		//新建JSONObject对象
		JSONObject result = new JSONObject();
		
		//产品表-取得产品基本信息
		Product product = productService.getById(productId);
		result.put("product", product);
		

		//根据coverImgId查询产品封面图片
		Image coverImage = imageService.getById(product.getCoverImgId());
		result.put("coverImage", coverImage);
		
		//产品图片中间表-取得产品图片信息集合
		QueryWrapper<ProductImage> productImageQueryWrapper = new QueryWrapper<ProductImage>();
		productImageQueryWrapper.eq("product_id", product.getProductId());
		List<ProductImage> productImages = productImageService.list(productImageQueryWrapper);
		
		//图片表-循环中间表根据图片ID取得图片详细信息
		List<Image> images = new ArrayList<Image>();
		for(int i = 0;i < productImages.size(); i ++){
			images.add(imageService.getById(productImages.get(i)));
        }
		result.put("image", images);
		
		return ResultInfo.success(result);
	}

	/**
     * 删除产品信息
     * @param productId 产品ID
     * @return
     */
	@Transactional
	@Override
	public ResultInfo deleteProductInfo(Integer productId) {
		//修改产品表DFLG
		Product product = productService.getById(productId);
		product.setDFlg(true);
		productService.updateById(product);
		
		//产品图片中间表-取得产品图片信息集合
		QueryWrapper<ProductImage> productImageQueryWrapper = new QueryWrapper<ProductImage>();
		productImageQueryWrapper.eq("product_id", productId);
		List<ProductImage> productImages = productImageService.list(productImageQueryWrapper);
		
		//图片表-循环中间表根据图片ID修改图片DFLG
		List<Image> images = new ArrayList<Image>();
		for(int i = 0;i < productImages.size(); i ++){
			images.add(imageService.getById(productImages.get(i)));
        }
		for(int i = 0;i < images.size(); i ++){
			images.get(i).setDFlg(true);
		}
		imageService.updateBatchById(images);
		
		return ResultInfo.success();
	}

	
	@Override
	public ResultInfo getProductsByPage(Product product,Integer current,Integer size,Integer endPrice) {
		//调用Page方法
		Page<ProductPagePojo> page = new Page<ProductPagePojo>(current,size);
		
		//new一个条件构造器 
		QueryWrapper<Product> queryWrapperProductPagePojo = new QueryWrapper<Product>();
		
		//将product_id大于0加入到检索条件（默认查询所有产品分页信息）
		queryWrapperProductPagePojo.gt("product_id", 0);
		
		//只查询d_flg不为0的
		queryWrapperProductPagePojo.eq("p.d_flg", 0);
		
		//当name不为空时，将name加入到检索条件
		if (null != product.getName()) {
			queryWrapperProductPagePojo.like("name", product.getName());
		}
		
		//当statu不为空时，将statu加入到检索条件中
		if (null != product.getStatu() ) {
			queryWrapperProductPagePojo.eq("p.statu", product.getStatu() );
		}
		
		//当categorys不为空时，将categorys加入到检索条件进行模糊查询
		if(null != product.getCategorys()) {
			queryWrapperProductPagePojo.like("categorys", product.getCategorys());
		}
		
		//当product.getPrice()不为空并且endPrice不为空，将二者加入到检索条件
		if (null != product.getPrice() && null != endPrice) {
			queryWrapperProductPagePojo.between("price", product.getPrice(), endPrice);
		//当endPrice不为空，将endPrice加入到检索条件
		}else if(null != endPrice){
			queryWrapperProductPagePojo.eq("price",  endPrice);
		//当product.getPrice()不为空，将product.getPrice()加入到检索条件
		}else if(null != product.getPrice()) {
			queryWrapperProductPagePojo.eq("price", product.getPrice());
		}
		//调用formatCategorys方法，将查询到的产品分页信息的categorys格式化后再返回
				Page<ProductPagePojo> productsByPage = productServiceImpl.getProductsByPage(page, queryWrapperProductPagePojo);
				List<ProductPagePojo> records = productsByPage.getRecords();
				for(int i = 0 ;i < records.size();i++) {
					String categorys = this.formatCategorys(records.get(i).getCategorys());
					records.get(i).setCategorys(categorys);
				}
				return ResultInfo.success(productsByPage);
		

		
		
	}
	
	
	@Transactional
	@Override
	public ResultInfo updateProduct(Product product, 
			String url, 
			Boolean imgStatu, 
			Boolean imgDflg, 
			JSONArray jsonArrayUrl) {
		//注意！前端传图片分为四种情况 有增删改 各个组合
		
		
		// 根据传来的product 进行表修改
		productService.updateById(product);
		
		//用于整合中间表数据 进行对表的新增
		ProductImage pImage = new ProductImage();
		pImage.setProductId(product.getProductId());
		
		//查productImage表 根据product 的 id 对应的 多个img_id
		
		QueryWrapper<ProductImage> queryWrapper = new QueryWrapper<ProductImage>();
		queryWrapper.eq("product_id", product.getProductId());
		
		//获取中间表 productid 对应 的 img_id 放入List<ProductImage>
		List<ProductImage> productImage = productImageService.list(queryWrapper);
			
		//根据id更改封面url  注意：数据库Product表中 CoverImgId是不为null的
		Image image = new Image();
		if (url != null) {
			Product pId = productService.getById(product.getProductId());
			image.setImgId(pId.getCoverImgId());
			image.setUrl(url);
			imageService.updateById(image);
		}
		
		
		//四种情况
		if (jsonArrayUrl != null) {
			
			//前传 2 后 2 修改url
			if (productImage != null && productImage.size() == jsonArrayUrl.size()) {
				for (int i = 0; i < productImage.size(); i++) {
					image.setImgId(productImage.get(i).getImgId());
					
					image.setUrl(jsonArrayUrl.get(i).toString()); 
					
					imageService.updateById(image);
				}
			}
			
			//前传2 后0 新增  两个表
			if (productImage == null) {
				for (int i = 0; i < jsonArrayUrl.size(); i++) {
					Image image2 = new Image();
					image2.setUrl(jsonArrayUrl.get(i).toString());
		            imageService.save(image2);
		            //存入中间表
		            pImage.setImgId(image2.getImgId());
		            productImageService.save(pImage);
		            
		        }
			//前传1 后2 修改Image的dflg 并且删除中间表多的数据
			}else if (jsonArrayUrl.size() < productImage.size()) {
				for (int i = 0; i < productImage.size(); i++) {
					
					//如果i大于jsonArrayUrl.size()-1 说明是对于的部分 要删除掉
					if (i > jsonArrayUrl.size()-1) {
						image.setImgId(productImage.get(i).getImgId());
						image.setDFlg(true);
						imageService.updateById(image);
				
						QueryWrapper<ProductImage> queryWrapper2 = new QueryWrapper<ProductImage>();
						queryWrapper2.eq("img_id", productImage.get(i).getImgId());
						productImageService.remove(queryWrapper2);
					}else {
						image.setImgId(productImage.get(i).getImgId());
						image.setUrl(jsonArrayUrl.get(i).toString());
						imageService.updateById(image);
					}
					
		        }
			//前传2 后1 执行 修改url 增加Iamge 和 中间表  
			}else if (jsonArrayUrl.size() > productImage.size()) {
				for (int i = 0; i < jsonArrayUrl.size(); i++) {
					
					//如果i大于productImage.size()-1 说明是对于的部分 要增加
					if (i > productImage.size()-1) {
						Image image3 = new Image();
						image3.setUrl(jsonArrayUrl.get(i).toString());
						imageService.save(image3);
						
						pImage.setImgId(image3.getImgId());
						productImageService.save(pImage);
					}else {
						image.setImgId(productImage.get(i).getImgId());
						image.setUrl(jsonArrayUrl.get(i).toString());
						imageService.updateById(image);
					}
					
		        }
			}
		}

		return ResultInfo.success();
	}
	
	/**
     * 查询level个数（1，2，3，4）
     * @param 
     * @return
     */
	@Override
	public ResultInfo getLevelNum() {
		QueryWrapper<Category> queryWrapperLevel = new QueryWrapper<Category>();
		queryWrapperLevel.gt("level", 0);
		Integer[] levelNums = productService.selectLevelNum(queryWrapperLevel);
		return ResultInfo.success(levelNums);
	}
	
	/**
     * 查询父级分类信息
     * @param 
     * @return: categoryId,name,level
     */
	@Override
	public ResultInfo getPList(Integer level) {
		QueryWrapper<Category> queryWrapperPList = new QueryWrapper<Category>();
		int pLevel = level - 1;
		queryWrapperPList.eq("level", pLevel);
		List<Category> pList = categoryService.list(queryWrapperPList);
		return ResultInfo.success(pList);
	}

	/**
     * 根据categoryId查询父级分类名称
     * @param 
     * @return: name
     */
	@Override
	public ResultInfo getPName(Integer categoryId) {
		Category category = categoryService.getById(categoryId);
		QueryWrapper<Category> queryWrapperPName = new QueryWrapper<Category>();
		queryWrapperPName.eq("category_id", category.getPId());
		Category pName = categoryService.getOne(queryWrapperPName);
		return ResultInfo.success(pName);
	}
	
	/**
     * 修改分类详情
     */
	@Override
	public ResultInfo updateCategoryInfo(Category category, String url, String contant) {
			
		//修改image表
		//新建image实体类
		Image image = new Image();
		//取img主键
		if (category.getImgId() != null) {
			image.setImgId(category.getImgId());
			//取Url地址
			image.setUrl(url);
			//设置image表
			imageService.updateById(image);
		} else {
			if (!StringUtils.isEmpty(url)) {
				image.setUrl(url);
				imageService.save(image);
				category.setImgId(image.getImgId());
			}
			
		}
		
		//修改category表
		categoryService.updateById(category);
		
		//修改category_detail表
		//新建category_detail实体类
		CategoryDetail categoryDetail =  new CategoryDetail();
		//条件构造器
		QueryWrapper<CategoryDetail> queryWrapper = new QueryWrapper<CategoryDetail>();
		queryWrapper.eq("category_id", category.getCategoryId());
		//详细内容
		categoryDetail.setContant(contant);
		//设置category_detail表
		categoryDetailService.update(categoryDetail, queryWrapper);
		
		return ResultInfo.success();
	}
	
	/**
	 * 新建产品信息
	 */
	@Transactional
	@Override
	public ResultInfo addProductInfo(Product product, String url, JSONArray urls) {
//		//jsonArray是list类型
//		//image表-根据URL新建image对象（封面图片）
		Image image = new Image();
		image.setUrl(url);
		imageService.save(image);
//		//将封面图片地址传入product中
		product.setCoverImgId(image.getImgId());
//		//product表-保存product信息
		productService.save(product);
	
		Image pImage = new Image();
//		ProductImage productImage = new ProductImage();
//		//image表-根据URLS新建多个image对象（产品图片）
//		for (int i = 0; i < urls.size(); i++) {
//			pImage.setUrl(urls.get(i).toString());
//			//先存image表
//			imageService.save(pImage);
//			//再存中间表的poductID
//			productImage.setProductId(product.getProductId());
//			//最后存中间表的imageID
//			productImage.setImgId(pImage.getImgId());
//			productImageService.save(productImage);
//		}
		return ResultInfo.success();
	}
	
	//微信端产品分页查询
		@Override
		public ResultInfo getProductsBycategoryId(Integer categoryId) {
			String id = "■"+categoryId+"■";
			//new一个page
			Page<ProductPagePojo> page = new Page<ProductPagePojo>(0,10);
			//new一个条件构造器 
			QueryWrapper<Product> queryWrapperProductPagePojo = new QueryWrapper<Product>();
			
			//将product_id大于0加入到检索条件（默认查询所有产品分页信息）
			queryWrapperProductPagePojo.gt("product_id", 0);
			
			//只查询d_flg不为0的
			queryWrapperProductPagePojo.eq("p.d_flg", 0);
			
			queryWrapperProductPagePojo.like("categorys", id);
			
			
			return ResultInfo.success(productServiceImpl.getProductsByPage(page, queryWrapperProductPagePojo)) ;
		}
}
